from flask import Flask, render_template, session, jsonify, request, redirect, url_for, Response
from module import Notification
from database import user_db, chat_history_db, competition_db
import os
import json
import uuid
import requests
from datetime import datetime, timedelta
from functools import wraps

# 导入扣子官方SDK
try:
    from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, ChatEventType, COZE_CN_BASE_URL
    COZE_SDK_AVAILABLE = True
except ImportError:
    COZE_SDK_AVAILABLE = False
    print("警告: 扣子SDK未安装，将使用备用方案")


app = Flask(__name__)
app.secret_key = os.urandom(24)
# 设置session过期时间为3天
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=3)

# 扣子智能体配置
COZE_CONFIG = {
    'api_url': 'https://api.coze.cn/v3/chat',
    'bot_id': '7535033719300931584',
    'api_key': 'pat_AXATexroR3mOoEKXkVnbJ0nkOPwyxKDTZtWL1P3nLUdyAM2kHG6QWFPwmEMKEQCy'
}

def update_competition_status():
    """
    根据比赛开始时间和当前时间更新比赛状态信息
    状态规则：
    - upcoming: 比赛还未开始
    - ongoing: 比赛正在进行中
    - finished: 比赛已结束
    """
    try:
        print("开始更新比赛状态...")
        
        # 使用数据库更新比赛状态
        success = competition_db.update_competition_status()
        
        if success:
            print("比赛状态更新完成")
        else:
            print("比赛状态更新失败")
        
        return success
        
    except Exception as e:
        print(f"更新比赛状态时出错: {e}")
        return False

def cleanup_expired_resumes():
    """
    清理过期的简历文件
    """
    try:
        print("开始清理过期简历...")
        
        # 获取所有用户的简历信息
        with user_db.db_manager.get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('SELECT student_id, resume_data FROM users WHERE resume_data IS NOT NULL')
            rows = cursor.fetchall()
            
            cleaned_count = 0
            for row in rows:
                student_id, resume_data_json = row
                if resume_data_json:
                    try:
                        resume_data = json.loads(resume_data_json)
                        expiry_date = datetime.fromisoformat(resume_data['expiry_date'])
                        
                        # 检查是否过期
                        if datetime.now() > expiry_date:
                            # 删除文件
                            file_path = resume_data.get('file_path')
                            if file_path and os.path.exists(file_path):
                                try:
                                    os.remove(file_path)
                                    print(f"删除过期简历文件: {file_path}")
                                except Exception as e:
                                    print(f"删除文件失败 {file_path}: {e}")
                            
                            # 清除数据库记录
                            user_db.update_resume(student_id, None)
                            cleaned_count += 1
                            print(f"清理用户 {student_id} 的过期简历")
                            
                    except Exception as e:
                        print(f"处理用户 {student_id} 简历数据时出错: {e}")
            
            print(f"简历清理完成，共清理 {cleaned_count} 个过期简历")
            return True
            
    except Exception as e:
        print(f"清理过期简历时出错: {e}")
        return False

# 登录验证装饰器
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            return redirect('/login')
        return f(*args, **kwargs)
    return decorated_function

def get_user():
    if 'user_id' not in session:
        return None
    
    user = user_db.get_user_by_student_id(session['user_id'])
    return user

@app.route('/login')
def login():
    if 'user_id' in session:
        return redirect('/')
    return render_template('login.html')

@app.route('/register')
def register():
    if 'user_id' in session:
        return redirect('/')
    # 读取学院与专业信息
    college_info = {}
    try:
        with open(os.path.join('data', 'college_info.json'), 'r', encoding='utf-8') as f:
            college_info = json.load(f)
    except Exception as e:
        print(f"加载college_info失败: {e}")
    return render_template('register.html', college_info=college_info)

@app.route('/logout')
def logout():
    session.clear()
    return redirect('/login')

@app.route('/')
@login_required
def index():
    user = get_user()
    if not user:
        return redirect('/login')
    return render_template('competitions.html', user=user)

@app.route('/notifications')
@login_required
def notifications():
    user = get_user()
    if not user:
        return redirect('/login')
    return render_template('notifications.html', user=user)

@app.route('/profile')
@login_required
def profile():
    user = get_user()
    if not user:
        return redirect('/login')
    # 读取学院与专业信息
    college_info = {}
    try:
        with open(os.path.join('data', 'college_info.json'), 'r', encoding='utf-8') as f:
            college_info = json.load(f)
    except Exception as e:
        print(f"加载college_info失败: {e}")
    return render_template('profile.html', user=user, college_info=college_info)

@app.route('/chat-history')
@login_required
def chat_history():
    user = get_user()
    if not user:
        return redirect('/login')
    return render_template('chat_history.html', user=user)

# 用户认证API
@app.route('/api/login', methods=['POST'])
def login_api():
    try:
        data = request.get_json()
        student_id = data.get('student_id')
        password = data.get('password')
        
        if not student_id or not password:
            return jsonify({'success': False, 'message': '请填写完整的登录信息'})
        
        # 验证用户
        user = user_db.authenticate_user(student_id, password)
        if user:
            session.permanent = True  # 启用永久session
            session['user_id'] = user['student_id']
            return jsonify({'success': True, 'message': '登录成功'})
        else:
            return jsonify({'success': False, 'message': '学号或密码错误'})
    except Exception as e:
        return jsonify({'success': False, 'message': '登录失败，请重试'})

@app.route('/api/register', methods=['POST'])
def register_api():
    try:
        data = request.get_json()
        student_id = data.get('student_id')
        name = data.get('name')
        password = data.get('password')
        college = data.get('college')
        major = data.get('major')
        phone = data.get('phone')
        
        if not student_id or not name or not password:
            return jsonify({'success': False, 'message': '请填写完整的注册信息'})
        
        # 验证学号格式（简单验证）
        if len(student_id) != 12:
            return jsonify({'success': False, 'message': '学号格式不正确'})
        
        # 验证密码长度
        if len(password) < 6:
            return jsonify({'success': False, 'message': '密码长度至少6位'})
        
        # 创建用户
        success, message = user_db.create_user(student_id, name, password, college, major, phone)
        if success:
            # 创建扣子用户变量
            try:
                user = user_db.get_user_by_student_id(student_id)
                if user:
                    create_coze_user_variables(student_id, user)
            except Exception as e:
                print(f"创建扣子用户变量失败: {e}")
            
            return jsonify({'success': True, 'message': message})
        else:
            return jsonify({'success': False, 'message': message})
    except Exception as e:
        return jsonify({'success': False, 'message': '注册失败，请重试'})

@app.route('/api/logout', methods=['POST'])
def logout_api():
    session.clear()
    return jsonify({'success': True, 'message': '退出成功'})

# 竞赛相关API
@app.route('/api/competitions')
def get_competitions():
    try:
        competitions = competition_db.get_all_competitions()
        return jsonify(competitions)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/competitions/search')
def search_competitions():
    """搜索竞赛（优化版本）"""
    query = request.args.get('q', '')
    category = request.args.get('category', '')
    status = request.args.get('status', '')
    rating = request.args.get('rating', '')
    sort = request.args.get('sort', '')
    
    try:
        competitions = competition_db.search_competitions(
            query=query,
            category=category,
            status=status,
            rating=rating
        )
        
        # 如果前端没有提供排序参数，返回原始数据让前端处理
        if not sort:
            return jsonify(competitions)
        
        # 后端排序（可选，如果前端排序性能足够的话可以注释掉）
        # competitions = sort_competitions_backend(competitions, sort)
        
        return jsonify(competitions)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/competitions/<int:comp_id>')
def get_competition_detail(comp_id):
    """获取竞赛详情"""
    try:
        competition = competition_db.get_competition_by_id(comp_id)
        if competition:
            return jsonify(competition)
        return jsonify({'error': '竞赛不存在'}), 404
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/competitions/categories')
def get_competition_categories():
    """获取所有竞赛分类"""
    try:
        categories = competition_db.get_all_categories()
        return jsonify(categories)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/competitions/upcoming')
def get_upcoming_competitions():
    """获取即将开始的竞赛"""
    try:
        competitions = competition_db.get_upcoming_competitions()
        return jsonify(competitions)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# 通知相关API
@app.route('/api/notifications')
@login_required
def get_notifications():
    """获取通知列表（与用户未读状态绑定）"""
    try:
        user_id = session.get('user_id')
        user = user_db.get_user_by_student_id(user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 获取用户的未读通知ID列表
        unread_set = set(user['unread_news']) if user['unread_news'] else set()
        
        # 加载所有通知
        notifications = Notification.load_from_json('data/notifications.json')
        result = []
        
        for notif in notifications:
            item = notif.to_dict()
            # 根据用户未读列表设置 is_read 字段
            # 如果通知ID在用户的未读列表中，则标记为未读
            item['is_read'] = notif.id not in unread_set
            result.append(item)
        
        return jsonify(result)
    except Exception as e:
        print(f"获取通知列表错误: {e}")
        return jsonify({'error': str(e)}), 500


@app.route('/api/notifications/mark-read', methods=['POST'])
@login_required
def mark_notification_read():
    """标记单条通知为已读（从当前用户未读列表中移除该ID）"""
    try:
        data = request.get_json() or {}
        notif_id = data.get('id')
        if notif_id is None:
            return jsonify({'success': False, 'message': '缺少通知ID'}), 400

        user_id = session.get('user_id')
        user = user_db.get_user_by_student_id(user_id)
        
        if not user:
            return jsonify({'success': False, 'message': '用户不存在'}), 404

        # 更新未读通知列表
        unread_news = user['unread_news'] or []
        if notif_id in unread_news:
            unread_news = [nid for nid in unread_news if nid != notif_id]
            user_db.update_unread_news(user_id, unread_news)

        return jsonify({'success': True})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500


@app.route('/api/notifications/mark-all-read', methods=['POST'])
@login_required
def mark_all_notifications_read():
    """将当前用户的所有通知标记为已读（清空未读列表）"""
    try:
        user_id = session.get('user_id')
        
        # 清空未读通知列表
        user_db.update_unread_news(user_id, [])

        return jsonify({'success': True})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

# 用户信息相关API
@app.route('/api/user/update', methods=['POST'])
@login_required
def update_user():
    """更新用户信息"""
    try:
        data = request.get_json()
        user_id = session.get('user_id')
        
        if not user_id:
            return jsonify({'error': '用户未登录'}), 401
        
        # 获取用户对象
        user = user_db.get_user_by_student_id(user_id)
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 构建更新数据
        update_data = {}
        if 'name' in data:
            update_data['name'] = data['name']
        if 'phone' in data:
            update_data['phone'] = data['phone']
        if 'college' in data:
            update_data['college'] = data['college']
        if 'major' in data:
            update_data['major'] = data['major']
        if 'profile' in data:
            update_data['profile'] = data['profile']
        
        # 更新用户信息
        if update_data:
            user_db.update_user(user_id, **update_data)
        
        # 获取更新后的用户信息
        updated_user = user_db.get_user_by_student_id(user_id)
        
        return jsonify({'success': True, 'user': updated_user})
    except Exception as e:
        print(f"更新用户信息错误: {e}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/user/avatar', methods=['POST'])
@login_required
def upload_avatar():
    """上传头像"""
    try:
        # 这里应该处理文件上传逻辑
        # 简化处理，直接返回成功
        return jsonify({'success': True, 'avatar_url': 'images/default_avatar.jpeg'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/user/resume', methods=['POST'])
@login_required
def upload_resume():
    """上传简历"""
    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'error': '用户未登录'}), 401
        
        # 检查是否有文件上传
        if 'resume' not in request.files:
            return jsonify({'error': '没有选择文件'}), 400
        
        file = request.files['resume']
        if file.filename == '':
            return jsonify({'error': '没有选择文件'}), 400
        
        # 检查文件类型
        allowed_extensions = {'pdf'}
        if not file.filename.lower().endswith('.pdf'):
            return jsonify({'error': '只支持PDF格式文件'}), 400
        
        # 检查文件大小（10MB限制）
        file.seek(0, 2)  # 移动到文件末尾
        file_size = file.tell()
        file.seek(0)  # 重置到文件开头
        
        if file_size > 10 * 1024 * 1024:  # 10MB
            return jsonify({'error': '文件大小不能超过10MB'}), 400
        
        # 生成唯一文件名
        file_extension = os.path.splitext(file.filename)[1]
        unique_filename = f"{user_id}_{int(datetime.now().timestamp())}{file_extension}"
        file_path = os.path.join('uploads', 'resumes', unique_filename)
        
        # 删除用户之前的简历文件
        user = user_db.get_user_by_student_id(user_id)
        if user and user.get('resume'):
            old_file_path = user['resume'].get('file_path')
            if old_file_path and os.path.exists(old_file_path):
                try:
                    os.remove(old_file_path)
                except Exception as e:
                    print(f"删除旧简历文件失败: {e}")
        
        # 保存新文件
        file.save(file_path)
        
        # 计算文件大小（MB）
        file_size_mb = round(file_size / (1024 * 1024), 2)
        
        # 设置过期时间（一周后）
        expiry_date = datetime.now() + timedelta(days=7)
        
        # 构建简历数据
        resume_data = {
            'file_name': file.filename,
            'file_path': file_path,
            'file_size': file_size_mb,
            'upload_date': datetime.now().isoformat(),
            'expiry_date': expiry_date.isoformat(),
            'file_size_bytes': file_size
        }
        
        # 更新数据库
        if user_db.update_resume(user_id, resume_data):
            return jsonify({
                'success': True, 
                'resume': resume_data,
                'message': '简历上传成功'
            })
        else:
            # 如果数据库更新失败，删除已上传的文件
            if os.path.exists(file_path):
                os.remove(file_path)
            return jsonify({'error': '保存简历信息失败'}), 500
            
    except Exception as e:
        print(f"上传简历错误: {e}")
        return jsonify({'error': '上传失败，请重试'}), 500

@app.route('/api/user/resume', methods=['DELETE'])
@login_required
def delete_resume():
    """删除简历"""
    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'error': '用户未登录'}), 401
        
        user = user_db.get_user_by_student_id(user_id)
        if not user or not user.get('resume'):
            return jsonify({'error': '没有找到简历文件'}), 404
        
        # 删除文件
        file_path = user['resume'].get('file_path')
        if file_path and os.path.exists(file_path):
            try:
                os.remove(file_path)
            except Exception as e:
                print(f"删除简历文件失败: {e}")
        
        # 清除数据库中的简历信息
        if user_db.update_resume(user_id, None):
            return jsonify({'success': True, 'message': '简历删除成功'})
        else:
            return jsonify({'error': '删除简历信息失败'}), 500
            
    except Exception as e:
        print(f"删除简历错误: {e}")
        return jsonify({'error': '删除失败，请重试'}), 500

@app.route('/api/user/resume', methods=['GET'])
@login_required
def get_resume():
    """获取简历信息"""
    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'error': '用户未登录'}), 401
        
        user = user_db.get_user_by_student_id(user_id)
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        resume = user.get('resume')
        if not resume:
            return jsonify({'success': True, 'resume': None})
        
        # 检查文件是否存在
        file_path = resume.get('file_path')
        if file_path and not os.path.exists(file_path):
            # 文件不存在，清除数据库记录
            user_db.update_resume(user_id, None)
            return jsonify({'success': True, 'resume': None})
        
        # 检查是否过期
        expiry_date = datetime.fromisoformat(resume['expiry_date'])
        if datetime.now() > expiry_date:
            # 文件过期，删除文件并清除记录
            if file_path and os.path.exists(file_path):
                try:
                    os.remove(file_path)
                except Exception as e:
                    print(f"删除过期简历文件失败: {e}")
            user_db.update_resume(user_id, None)
            return jsonify({'success': True, 'resume': None})
        
        return jsonify({'success': True, 'resume': resume})
        
    except Exception as e:
        print(f"获取简历信息错误: {e}")
        return jsonify({'error': '获取简历信息失败'}), 500

# AI聊天相关API
@app.route('/api/ai/chat', methods=['POST'])
@login_required
def ai_chat():
    """AI聊天接口"""
    try:
        data = request.get_json()
        message = data.get('message', '')
        conversation_id = data.get('conversation_id')
        
        if not message:
            return jsonify({'error': '消息不能为空'}), 400
        
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'error': '用户未登录'}), 401
        
        # 获取或创建对话
        if not conversation_id:
            # 创建新对话
            title = message[:30] + '...' if len(message) > 30 else message
            conversation_id = chat_history_db.create_conversation(user_id, title)
            if not conversation_id:
                return jsonify({'error': '创建对话失败'}), 500
        
        # 添加用户消息
        chat_history_db.add_message(conversation_id, 'user', message)
        
        # 连接到扣子智能体
        try:
            # 检查SDK是否可用
            if not COZE_SDK_AVAILABLE:
                response = "抱歉，扣子SDK未安装，请联系管理员。"
            else:
                # 使用官方扣子SDK，扣子会自动使用已创建的用户变量
                print(f"使用扣子SDK进行聊天，用户ID: {user_id}, 消息: {message}")
                coze = Coze(
                    auth=TokenAuth(token=COZE_CONFIG['api_key']), 
                    base_url=COZE_CN_BASE_URL
                )
                
                # 调用聊天接口
                print("开始调用扣子聊天接口...")
                chat_response = coze.chat.create(
                    bot_id=COZE_CONFIG['bot_id'],
                    user_id=user_id,
                    additional_messages=[
                        Message.build_user_question_text(message),
                    ],
                )
                
                print(f"扣子聊天响应: {chat_response}")
                
                # 获取回复内容
                if hasattr(chat_response, 'message') and chat_response.message:
                    response = chat_response.message.content
                    print(f"获取到回复内容，长度: {len(response)}")
                else:
                    response = "抱歉，我暂时无法理解您的问题。请尝试询问关于竞赛、报名、时间或帮助相关的问题。"
                    print("未获取到有效回复内容")
                    
        except Exception as e:
            # 异常时的备用回复
            print(f"扣子聊天异常: {e}")
            response = f"抱歉，智能助手出现异常：{str(e)}"
        
        # 添加AI回复
        chat_history_db.add_message(conversation_id, 'ai', response)
        
        return jsonify({
            'success': True,
            'response': response,
            'conversation_id': conversation_id,
            'timestamp': datetime.now().isoformat()
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/chat/history')
@login_required
def get_chat_history():
    """获取聊天历史"""
    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'error': '用户未登录'}), 401
        
        conversations = chat_history_db.get_chat_history(user_id)
        
        return jsonify({
            'success': True,
            'conversations': conversations
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/chat/conversation/<conversation_id>', methods=['GET', 'DELETE'])
@login_required
def delete_conversation(conversation_id):
    """获取对话详情或删除对话"""
    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'error': '用户未登录'}), 401

        if request.method == 'GET':
            # 返回完整对话详情（包含全部消息，按时间升序）
            conversations = chat_history_db.get_chat_history(user_id)
            for conv in conversations:
                if conv.get('id') == conversation_id:
                    # 确保按时间升序
                    conv['messages'] = sorted(conv.get('messages', []), key=lambda m: m.get('timestamp') or '')
                    return jsonify({'success': True, 'conversation': conv})
            return jsonify({'error': '对话不存在'}), 404

        # DELETE
        success = chat_history_db.delete_conversation(user_id, conversation_id)
        if success:
            return jsonify({'success': True})
        else:
            return jsonify({'error': '对话不存在'}), 404
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/profile/update', methods=['POST'])
@login_required
def update_profile():
    """更新个人资料"""
    try:
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'error': '用户未登录'}), 401
        
        data = request.get_json()
        
        # 获取用户数据
        user = user_db.get_user_by_student_id(user_id)
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 构建更新数据
        update_data = {}
        if 'name' in data:
            update_data['name'] = data['name']
        if 'college' in data:
            update_data['college'] = data['college']
        if 'major' in data:
            update_data['major'] = data['major']
        if 'phone' in data:
            update_data['phone'] = data['phone']
        if 'profile' in data:
            update_data['profile'] = data['profile']
        
        # 更新用户信息
        if update_data:
            user_db.update_user(user_id, **update_data)
        
        # 同步更新扣子用户变量
        try:
            updated_user = user_db.get_user_by_student_id(user_id)
            update_coze_user_variables(user_id, updated_user)
        except Exception as e:
            print(f"更新扣子用户变量失败: {e}")
        
        return jsonify({'success': True, 'message': '个人资料更新成功'})
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500





def update_coze_user_variables(user_id, user):
    """更新扣子用户变量"""
    try:
        if not COZE_SDK_AVAILABLE:
            print("扣子SDK不可用，跳过用户变量更新")
            return
        
        # 构建用户变量数据
        user_variables_data = [
            {"keyword": "name", "value": user.get('name') or ""},
            {"keyword": "grade", "value": str(user.get('grade')) if user.get('grade') else ""},
            {"keyword": "college", "value": user.get('college') or ""},
            {"keyword": "major", "value": user.get('major') or ""},
            {"keyword": "resume", "value": "已上传" if user.get('resume') else "未上传"},
        ]
        
        # 调用扣子API更新用户变量值
        variables_url = "https://api.coze.cn/v1/variables"
        headers = {
            "Authorization": f"Bearer {COZE_CONFIG['api_key']}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "bot_id": COZE_CONFIG['bot_id'],
            "connector_id": "1024",  # API渠道
            "connector_uid": user_id,
            "data": user_variables_data
        }
        
        print(f"正在更新扣子用户变量，用户ID: {user_id}")
        print(f"请求数据: {payload}")
        
        response = requests.put(variables_url, headers=headers, json=payload, timeout=30)
        
        if response.status_code == 200:
            result = response.json()
            if result.get('code') == 0:
                print(f"✅ 扣子用户变量更新成功: {result}")
            else:
                print(f"❌ 扣子用户变量更新失败: {result}")
        else:
            print(f"❌ 扣子API请求失败，状态码: {response.status_code}")
            print(f"错误信息: {response.text}")
        
    except Exception as e:
        print(f"更新扣子用户变量异常: {e}")
        import traceback
        traceback.print_exc()

def create_coze_user_variables(user_id, user):
    """创建扣子用户变量"""
    try:
        if not COZE_SDK_AVAILABLE:
            print("扣子SDK不可用，跳过用户变量创建")
            return
        
        coze = Coze(
            auth=TokenAuth(token=COZE_CONFIG['api_key']), 
            base_url=COZE_CN_BASE_URL
        )
        
        # 构建用户变量数据
        user_variables_data = [
            {"keyword": "name", "value": user.get('name') or ""},
            {"keyword": "grade", "value": str(user.get('grade')) if user.get('grade') else ""},
            {"keyword": "college", "value": user.get('college') or ""},
            {"keyword": "major", "value": user.get('major') or ""},
            {"keyword": "resume", "value": "已上传" if user.get('resume') else "未上传"},
            {"keyword": "phone", "value": user.get('phone') or ""}
        ]
        
        # 调用扣子API设置用户变量值
        variables_url = "https://api.coze.cn/v1/variables"
        headers = {
            "Authorization": f"Bearer {COZE_CONFIG['api_key']}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "bot_id": COZE_CONFIG['bot_id'],
            "connector_id": "1024",  # API渠道
            "connector_uid": user_id,
            "data": user_variables_data
        }
        
        print(f"正在创建扣子用户变量，用户ID: {user_id}")
        print(f"请求数据: {payload}")
        
        response = requests.put(variables_url, headers=headers, json=payload, timeout=30)
        
        if response.status_code == 200:
            result = response.json()
            if result.get('code') == 0:
                print(f"✅ 扣子用户变量创建成功: {result}")
            else:
                print(f"❌ 扣子用户变量创建失败: {result}")
        else:
            print(f"❌ 扣子API请求失败，状态码: {response.status_code}")
            print(f"错误信息: {response.text}")

    except Exception as e:
        print(f"创建扣子用户变量异常: {e}")
        import traceback
        traceback.print_exc()

@app.route('/api/coze/test')
@login_required
def test_coze_connection():
    """测试扣子智能体连接"""
    try:
        # 简单的测试消息
        test_message = "你好，请简单介绍一下你自己"
        
        coze_headers = {
            "Authorization": f"Bearer {COZE_CONFIG['api_key']}",
            "Content-Type": "application/json"
        }
        
        coze_data = {
            "bot_id": COZE_CONFIG['bot_id'],
            "user_id": "test_user",
            "stream": False,
            "additional_messages": [
                {
                    "content": test_message,
                    "content_type": "text",
                    "role": "user",
                    "type": "question"
                }
            ],
            "parameters": {}
        }
        
        # 测试连接
        coze_response = requests.post(COZE_CONFIG['api_url'], headers=coze_headers, json=coze_data, timeout=10)
        
        if coze_response.status_code == 200:
            coze_result = coze_response.json()
            return jsonify({
                'success': True,
                'message': '扣子智能体连接成功',
                'response': coze_result
            })
        else:
            return jsonify({
                'success': False,
                'message': f'扣子智能体连接失败，状态码: {coze_response.status_code}',
                'error': coze_response.text
            }), 500
            
    except requests.exceptions.RequestException as e:
        return jsonify({
            'success': False,
            'message': '网络连接异常',
            'error': str(e)
        }), 500
    except Exception as e:
        return jsonify({
            'success': False,
            'message': '测试过程中出现异常',
            'error': str(e)
        }), 500

@app.route('/api/ai/chat/stream', methods=['POST'])
@login_required
def ai_chat_stream():
    """AI聊天流式接口 - 使用官方扣子SDK"""
    try:
        data = request.get_json()
        message = data.get('message', '')
        conversation_id = data.get('conversation_id')
        
        if not message:
            return jsonify({'error': '消息不能为空'}), 400
        
        user_id = session.get('user_id')
        if not user_id:
            return jsonify({'error': '用户未登录'}), 401
        
        # 获取或创建对话
        if not conversation_id:
            # 创建新对话
            title = message[:30] + '...' if len(message) > 30 else message
            conversation_id = chat_history_db.create_conversation(user_id, title)
            if not conversation_id:
                return jsonify({'error': '创建对话失败'}), 500
        
        # 等待信息传输完毕
        pending_user_message = message
        # 添加用户消息
        chat_history_db.add_message(conversation_id, 'user', message)
        
        def generate_stream():
            try:
                # 检查SDK是否可用
                if not COZE_SDK_AVAILABLE:
                    error_msg = "抱歉，扣子SDK未安装，请联系管理员。"
                    yield f"data: {json.dumps({'content': error_msg, 'type': 'error'})}\n\n"
                    return
                
                # 使用官方扣子SDK
                coze = Coze(
                    auth=TokenAuth(token=COZE_CONFIG['api_key']), 
                    base_url=COZE_CN_BASE_URL
                )
                
                full_response = ""

                # 调用流式聊天接口，扣子会自动使用已创建的用户变量
                print("开始调用扣子流式聊天接口...")
                for event in coze.chat.stream(
                    bot_id=COZE_CONFIG['bot_id'],
                    user_id=user_id,
                    additional_messages=[
                        Message.build_user_question_text(message),
                    ],
                ):
                    if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
                        # 处理流式内容
                        content = event.message.content
                        if content:
                            full_response += content
                            print(content, end='')
                            # 发送流式数据
                            yield f"data: {json.dumps({'content': content, 'type': 'chunk'})}\n\n"
                    
                    elif event.event == ChatEventType.CONVERSATION_CHAT_COMPLETED:
                        # 聊天完成
                        break
                
                print(f"扣子SDK完成，总回复长度: {len(full_response)}")
                
                # 发送完成信号（客户端据此结束渲染）
                yield f"data: {json.dumps({'content': '', 'type': 'done', 'conversation_id': conversation_id})}\n\n"

                # 接收完后统一写入到数据库：先写入用户消息，再写入AI完整回复
                if full_response.strip():
                    try:
                        chat_history_db.add_message(conversation_id, 'ai', full_response.strip())
                    except Exception as _:
                        print("保存聊天记录失败（流式完成后）")
                else:
                    print("警告：未收到有效回复内容")
                        
            except Exception as e:
                # 异常：告知前端错误，并将用户消息与错误信息写入历史（保证可追溯）
                error_msg = f"抱歉，智能助手出现异常：{str(e)}"
                print(f"流式聊天异常: {e}")
                try:
                    chat_history_db.add_message(conversation_id, 'ai', error_msg)
                except Exception as _:
                    print("保存异常聊天记录失败")
                yield f"data: {json.dumps({'content': error_msg, 'type': 'error'})}\n\n"
        
        # 返回流式响应
        return Response(
            generate_stream(),
            mimetype='text/event-stream',
            headers={
                'Cache-Control': 'no-cache',
                'Connection': 'keep-alive',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Headers': 'Cache-Control'
            }
        )
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    # 应用启动时更新比赛状态和清理过期简历
    print("应用启动中，正在更新比赛状态...")
    update_competition_status()
    print("正在清理过期简历...")
    cleanup_expired_resumes()
    print("启动Flask应用...")
    
    app.run(host="0.0.0.0", port=5000)